<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="方案名称" prop="schemeName">
        <el-input
          v-model="queryParams.schemeName"
          placeholder="请输入方案名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="方案编号" prop="schemePlan">
        <el-input
          v-model="queryParams.schemePlan"
          placeholder="请输入方案编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="有效期" prop="isbalance">
        <el-select v-model="queryParams.isbalance" placeholder="请选择有效期">
          <el-option v-for="dict in dict.type.sys_yxq_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:scheme:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:scheme:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:scheme:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:scheme:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schemeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="方案名称" align="center" prop="schemeName" />
      <el-table-column label="方案编号" align="center" prop="schemePlan" />
      <el-table-column label="有效期" align="center" prop="yxq">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yxq_type" :value="scope.row.yxq"/>
        </template>
      </el-table-column>
      <el-table-column label="录入日期" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSchemeDetails(scope.row)"
            v-hasPermi="['system:scheme:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:scheme:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:scheme:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改方案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="方案名称" prop="schemeName">
              <el-input v-model="form.schemeName" placeholder="请输入方案名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期">
              <el-select v-model="form.yxq" placeholder="请选择有效期">
                <el-option v-for="dict in dict.type.sys_yxq_type" :key="dict.value" :label="dict.label" :value="Number(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关联门店">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScheme, getScheme, delScheme, addScheme, updateScheme } from "@/api/system/scheme";
import { deptTreeSelect } from "@/api/system/user";

export default {
  name: "Scheme",
  dicts: ['sys_yes_no_num', 'sys_yxq_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 方案表格数据
      schemeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 部门树选项
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      deptExpand: true,
      deptNodeAll: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schemeName: null,
        schemePlan: null,
        deptId: null,
        userId: null,
        isbalance: null,
        istimes: null,
        isdiscount: null,
        isequity: null,
        isscore: null,
        yxq: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        schemeName: [
          { required: true, message: "方案名称不能为空", trigger: "blur" }
        ],
        /*isbalance: [
          { required: true, message: "是否储值卡不能为空", trigger: "blur" }
        ],
        istimes: [
          { required: true, message: "是否次卡不能为空", trigger: "blur" }
        ],
        isdiscount: [
          { required: true, message: "是否折扣卡不能为空", trigger: "blur" }
        ],
        isequity: [
          { required: true, message: "是否权益卡不能为空", trigger: "blur" }
        ],
        isscore: [
          { required: true, message: "是否积分卡不能为空", trigger: "blur" }
        ]*/
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询方案列表 */
    getList() {
      this.loading = true;
      listScheme(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.schemeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        schemeId: null,
        schemeName: null,
        schemePlan: null,
        deptId: null,
        userId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isbalance: null,
        istimes: null,
        isdiscount: null,
        isequity: null,
        isscore: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.schemeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDeptTree();
      this.open = true;
      this.title = "添加方案";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getDeptTree();
      const schemeId = row.schemeId || this.ids
      getScheme(schemeId).then(response => {
        this.form = response.schemes;
        this.open = true;
        this.title = "修改方案";
        this.$nextTick(() => {
          this.$refs.dept.setCheckedKeys(response.checkedKeys);
        })
      })
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.deptOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    /** 查询部门树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTreeCheck(row) {
      return getDeptTreeCheck(row.schemePlan).then(response => {
        return response;
      });
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      // let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.deptIds = this.getDeptAllCheckedKeys();
          if (this.form.schemeId != null) {
            updateScheme(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScheme(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 查看详情操作 */
    handleSchemeDetails: function(row) {
      const schemeId = row.schemeId;
      this.$router.push("/system/scheme-details/scheme/" + schemeId);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const schemeIds = row.schemeId || this.ids;
      this.$modal.confirm('是否确认删除方案编号为"' + schemeIds + '"的数据项？').then(function() {
        return delScheme(schemeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/scheme/export', {
        ...this.queryParams
      }, `scheme_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
